package com.yanqu.road.server.cmd.grandchild;

import com.yanqu.road.entity.grandchild.JoinExamGrandChild;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.grandchild.GrandChildProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.grandchild.GrandChildMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameProtocol;

import java.math.BigInteger;

@Cmd(code = CrossProtocol.C_GRAND_CHILD_JOIN_IMPERIAL_EXAM, desc = "跨服参加科举考试")
public class CrossJoinExamCmd extends CrossCommand {

    private long userId;
    private long examNo;
    private JoinExamGrandChild child = null;
    private UserBaseInfo userBaseInfo;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        userId = packet.getPlayerId();

        GrandChildProto.CrossJoinExamReqMsg req = GrandChildProto.CrossJoinExamReqMsg.parseFrom(packet.getBytes());

        examNo = Long.valueOf(req.getNo());

        child = new JoinExamGrandChild();
        child.setId(req.getId());
        child.setAppearanceId(req.getAppearanceId());
        userBaseInfo = PlayerBasePb.parseToUserBaseInfo(req.getUserBaseInfo());
        child.setNickName(req.getName());
        child.setEarnSpeed(new BigInteger(req.getEarnSpeed()));
        child.setUserId(userId);
        child.setExamNo(examNo);
        if (req.hasBuff()) {
            child.setBuff(req.getBuff());
        }

        // 容错
        if (child.getEarnSpeed().compareTo(BigInteger.ZERO) == 0) {
            child.setEarnSpeed(BigInteger.ONE);
        }

        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        CrossUserMgr.updateUserBaseInfo(userId, userBaseInfo);
        ret = GrandChildMgr.joinExam(serverId, examNo, child);
    }

    @Override
    public void sendData() {
        GrandChildProto.CrossJoinExamRespMsg.Builder builder = GrandChildProto.CrossJoinExamRespMsg.newBuilder();
        builder.setRet(ret);
        builder.setChildId(child.getId());
        builder.setExamNo(examNo);
        YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_GRAND_CHILD_JOIN_IMPERIAL_EXAM_FROM_CROSS, builder);
        MessageHelper.sendPacket(serverId, userId, message);
    }
}
